<?php
namespace app\admin\model;  
use think\Model;
use think\Db;  
use app\admin\model\Paperdetail;
use app\admin\model\Choice;
use app\admin\model\Fillblank;
use app\admin\model\Judge;
use app\admin\model\Shortanswer;
use think\Session;
use think\Exception;

class Paper extends model
{
	protected $autoWriteTimestamp = 'datetime';
	protected $error = '';
	protected function initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::initialize();
        //TODO:自定义的初始化
    }
     /**
     * 保存试卷数据
     * @access public
     * @param array     $data  试卷基本信息
     * @param array     $datadetail  试卷详细信息
     * @return bool
     */
    public function saveData($data,$datadetail){
    	//也可以手动控制事务，例如：
		$this->error = '';
		if (empty($data) || empty($datadetail)) {
			$this->$error = '参数不能为空';
		}
		// 启动事务
		Db::startTrans();
		try{
		    $id = Db::table('paper')->insertGetId($data);
            if($id > 0){
                $datadetail['paperid'] = $id;
                $detail = new Paperdetail;
                if($detail->saveDataDetail($datadetail)){
                    //修改试题paperid字段,添加一个新的
                    unset($datadetail['paperid']);
                    foreach($datadetail as $key=> $value){
                        switch($key){
                            case 'single':
                                $single = new Choice;
                                $re = $single->updatePaperId($value,$id);
                                break;
                            case 'mul':
                                $single = new Choice;
                                $re =  $single->updatePaperId($value,$id);
                                break;
                            case 'ide':
                                $single = new Choice;
                                $re = $single->updatePaperId($value,$id);
                                break;
                            case 'fill':
                                $fill = new Fillblank;
                                $re = $fill->updatePaperId($value,$id);
                                break;
                            case 'judge':
                                $judge = new Judge;
                                $re = $judge->updatePaperId($value,$id);
                                break;
                            case 'short':
                                $short = new Shortanswer;
                                $re = $short->updatePaperId($value,$id);
                                break;
                        }
                        if(!$re) {
                            throw new Exception("试题表更新失败");
                        }
                    }

                    // 提交事务
                    Db::commit();

                }else{
                    throw new Exception("试卷详细信息添加失败");
                }
            }else{
                throw new Exception("试卷基础信息添加失败");
            }
		} catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
            $this->error = $e->getMessage();
		}
		return empty($error) ? true : false;
    }

    /**
     * 返回错误信息
     * @access public
     * @return string
     */
    public function getError(){
    	return $this->error;
    }
    /**
     * 返回试卷列表
     * @access public
     * @return array
     */
    public function getList(){
        $creater = Session::get('id');
        $data = Db::table('paper')
            ->where('creater',$creater)
            ->field('id,title,allscore,timelimit,singlenum,mulnum,fillnum,shortnum,judgenum,idenum,create_time,case is_publish when "0" THEN "未发布" when "1" THEN "已发布" end as publish')
            ->select();
        return $data;
    }
    /**
     * 返回试卷所有信息
     * @access public
     * @return array
     */
    public function getAllQusetion($id){
        $this->error = '';
        if($id){
            $data = Db::table('paper')
                ->alias('a')
                ->join('paperdetail w','a.id = w.paperid')
                ->where('a.id',$id)
                ->field('a.title,a.allscore,a.timelimit,a.singlenum,a.mulnum,a.fillnum,a.shortnum,a.judgenum,a.idenum,w.single,w.mul,w.ide,w.fill,w.judge,w.short')
                ->find();
        }else{
            $this->error = '参数错误';
        }
        return empty($error) ? $data : false;
    }

    /**
     * 删除试卷
     * @access public
     * @param $id
     * @return bool
     */
    public function delPaper($id){
        $this->error = '';
        //开启事务
        Db::startTrans();
        try{
            //删除试卷
            $resid = Db::table('paper')->where('id',$id)->delete();
            if($resid > 0){

                $detail = new Paperdetail;
                $data = $detail->getInfoById($id);
                if($data){
                    foreach($data as $key=> $value){
                        switch($key){
                            case 'single':
                                $single = new Choice;
                                $re = $single->delPaperId($value,$id);
                                break;
                            case 'mul':
                                $single = new Choice;
                                $re =  $single->delPaperId($value,$id);
                                break;
                            case 'ide':
                                $single = new Choice;
                                $re = $single->delPaperId($value,$id);
                                break;
                            case 'fill':
                                $fill = new Fillblank;
                                $re = $fill->delPaperId($value,$id);
                                break;
                            case 'judge':
                                $judge = new Judge;
                                $re = $judge->delPaperId($value,$id);
                                break;
                            case 'short':
                                $short = new Shortanswer;
                                $re = $short->delPaperId($value,$id);
                                break;
                        }
                        if(!$re) {
                            throw new Exception("试题表更新失败");
                        }
                    }
                    $res = $detail->delDetail($id);//删除试卷详细信息
                    if($res > 0){
                        // 提交事务
                        Db::commit();
                    }else{
                        throw new Exception("paperdetail错误");
                    }
                }else{
                    throw new Exception('no info');
                }
            }else{
                throw new Exception("试卷删除失败");
            }
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            $this->error = $e->getMessage();
        }
        return empty($this->error) ? true : false;
    }


}
